package net.wantongtech.xa.uploadbasicinfo.service;

import com.google.common.io.Files;
import com.wtkj.vo.dzzf.base.xxjh.MessageSend;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.StatsErrorIntegratedTransOutDataDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 统计错误的合并交易服务实现
 *
 * @author MaShibo
 * 日期 :  2020/2/6
 */
@Slf4j
@Service
public class StatsErrorIntegratedTransOutDataService {

    @Resource
    private StatsErrorIntegratedTransOutDataDao statsErrorIntegratedTransOutDataDao;

    /**
     * 处理错误数据
     *
     * @param filePath 文件路径
     */
    @SuppressWarnings("UnstableApiUsage")
    @Transactional(rollbackFor = Throwable.class)
    public void stats(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            log.warn("文件：{}，不存在，结束处理", file);
            return;
        }
        List<String> errorIntegratedIdList;
        try {
            errorIntegratedIdList = Files.readLines(file, Charset.forName("UTF-8"));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return;
        }

        log.info("共获取到{}个integratedId", errorIntegratedIdList.size());

        List<MessageSend> messageSendList = statsErrorIntegratedTransOutDataDao.queryErrorMessageSend(errorIntegratedIdList);
        log.info("共查询到{}条发送表数据记录", messageSendList.size());
        if (messageSendList.isEmpty()) {
            return;
        }

        //尚未发送的
        List<MessageSend> noneSendList = messageSendList
                .stream()
                .filter(messageSend -> messageSend.getSend() != 1)
                .collect(Collectors.toList());

        log.info("共有{}条尚未发送的发送表记录", noneSendList.size());

        //尚未发送的ID
        String noneSendIdJoining = noneSendList
                .stream()
                .map(messageSend -> String.format("'%s'", messageSend.getListId()))
                .collect(Collectors.joining(","));
        log.info("尚未发送的发送表ID：{}", noneSendIdJoining);


        List<String> noSentIntegratedIdList = statsErrorIntegratedTransOutDataDao.queryNoSentIntegratedId(noneSendIdJoining);
        log.info("共查询出{}条对应的尚未发送或发送失败的合并交易记录", noSentIntegratedIdList.size());

        for (String noSentIntegratedId : noSentIntegratedIdList) {

            //合并错误
            if (errorIntegratedIdList.contains(noSentIntegratedId)) {
                log.info("错误的合并交易ID：{}", noSentIntegratedId);
                //删除对应的合并交易记录
                statsErrorIntegratedTransOutDataDao.deleteIntegratedTransOutById(noSentIntegratedId);

                //恢复对应portalTransOut为未发送状态
                statsErrorIntegratedTransOutDataDao.resetPortalTransOutIntegratedInfo(noSentIntegratedId);

                //未合并错误
            } else {
                statsErrorIntegratedTransOutDataDao.resetIntegratedTransOutSendInfo(noSentIntegratedId);
            }
        }

        log.info("开始删除发送表记录");
        noneSendList.forEach(messageSend -> statsErrorIntegratedTransOutDataDao.deleteMessageSendById(messageSend.getListId()));
        log.info("发送表记录删除完成");

    }

}
